#define  _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode* build(vector<int>& inorder, vector<int>& postorder, int& posti, int inbegin, int inend)
    {
        if (inbegin > inend)
            return nullptr;

        TreeNode* root = new TreeNode(postorder[posti]);

        int rooti = inbegin;
        while (rooti <= inend)
        {
            if (inorder[rooti] == postorder[posti])
            {
                break;
            }
            ++rooti;
        }

        //[inbeign,rooti-1] rooti [rooti+1,inend]
        --posti;
        root->right = build(inorder, postorder, posti, rooti + 1, inend);
        root->left = build(inorder, postorder, posti, inbegin, rooti - 1);

        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
    {
        int i = postorder.size() - 1;
        return build(inorder, postorder, i, 0, inorder.size() - 1);
    }
};